package io.github.talelin.latticy.common;

import io.github.talelin.autoconfigure.exception.AuthenticationException;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.entity.Group;
import io.github.talelin.latticy.entity.User;
import io.github.talelin.latticy.entity.UserGroup;
import io.github.talelin.latticy.model.GroupDO;
import io.github.talelin.latticy.model.UserDO;
import io.github.talelin.latticy.repository.GroupRepository;
import io.github.talelin.latticy.repository.UserGroupRepository;
import io.github.talelin.latticy.repository.UserRepository;
import io.github.talelin.latticy.vo.GroupIsUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserUtil {

    @Autowired
    private GroupRepository groupRepository;

    @Autowired
    private UserGroupRepository userGroupRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     *
     * @return
     */
    public Boolean userAuthority() {
        Long userId = UserUtil.getCurrentUserId();
        List<Long> groupId = userGroupRepository.findGroupIdByUserId(userId);
        List<String> levels = groupRepository.findLevelByIdIn(groupId);
        if (levels.contains("guest")) {
            throw new AuthenticationException(10001);
        }
        return true;
    }

    /**
     * 当前用户ID
     * @return
     */
    public static Long getCurrentUserId() {
        UserDO user = LocalUser.getLocalUser();
        if (user == null) {
            throw new NotFoundException(10021);
        }
        return user.getId();
    }

    /**
     * root用户ID
     * @return
     */
    public Long getRootUserId() {
        Group group = groupRepository.findFirstByLevel("root");
        if (group == null) {
            throw new NotFoundException(20003);
        }
        UserGroup userGroup = userGroupRepository.findFirstByGroupId(group.getId());
        if (userGroup == null) {
            throw new NotFoundException(20003);
        }
        return userGroup.getUserId();
    }

    /**
     * 获取user用户
     * @return
     */
    public List<GroupIsUserVO> getUsers() {
        List<String> level = new ArrayList<>();
        level.add("root");
        level.add("user");
        List<Long> groupId = groupRepository.findByLevelIn(level);
        if (groupId == null) {
            throw new NotFoundException(20003);
        }
        List<Long> userId = userGroupRepository.findUserIdByGroupId(groupId);
        if (userId == null) {
            throw new NotFoundException(20003);
        }
        List<User> userList = userRepository.findByIdIn(userId);
        if (userList == null) {
            throw new NotFoundException(10021);
        }
        return GroupIsUserVO.getList(userList);
    }



}
